package com.weex.app.hotreload;

import android.text.TextUtils;

import com.taobao.weex.utils.WXLogUtils;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ws.WebSocket;
import okhttp3.ws.WebSocketCall;

/**
 * @author moxun
 * @date 29/12/2017
 */

public class HotReloadManager {
    private static final String TAG = "HotReloadManager";
    private WebSocket session;

    public HotReloadManager(String ws, final ActionListener actionListener) {
        if (TextUtils.isEmpty(ws) || actionListener == null) {
            WXLogUtils.w("HotReloadManager", "Illegal arguments");
            return;
        }

        OkHttpClient client = new OkHttpClient();
        Request.Builder builder = new Request.Builder();
        builder.url(ws);
        Request request = builder.build();
        WebSocketCall call = WebSocketCall.create(client, request);
        call.enqueue(new MyWebSocketListener(session, actionListener));
    }

    public void destroy() {
        if (session != null) {
            try {
                session.close(1001, "GOING_AWAY");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public interface ActionListener {
        void reload();

        void render(String bundleUrl);
    }
}
